<template>
  <div>
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item label="模型名称" prop="fileList">
        <a-upload :file-list="form.fileList"  :remove="handleRemove" :multiple="false"  accept=".zip,.bpmn20.xml,.bpmn,.bar" :before-upload="beforeUpload">
          <a-button> <a-icon type="upload" />选择文件</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="模型分类" prop="categoryId">
        <category-select v-model="form.categoryId"></category-select>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
import { importFile } from '@/api/process'
import CategorySelect from '@/views/process/category/components/CategorySelect'
export default {
  name: 'ModelForm',
  components: { CategorySelect },
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      form: {
        categoryId: '',
        fileList: []
      },
      rules: {
        fileList: [{ required: true, type: 'array', message: '请选择文件', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择模型分类', trigger: 'change' }]
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = new FormData()
          formData.append('file', this.form.fileList[0])
          formData.append('categoryId', this.form.categoryId)
          importFile(formData).then(res => {
            res.success ? this.$message.success('导入成功') : this.$message.error('导入失败')
            this.$emit('done', res.success)
          }).catch(res => {
            this.$emit('done', res.success)
          })
        } else {
          this.$emit('done', false)
          return false
        }
      })
    },
    resetForm() {
      // 重置表单数据
      this.form.fileList = []
      this.$refs.ruleForm.resetFields()
      this.$utils.merge(this.form, this.$options.data()['form'])
    },
    loadData(data) {
      if (data) {
        this.$utils.merge(this.form, data)
      }
    },
    handleRemove(file) {
      const index = this.form.fileList.indexOf(file)
      const newFileList = this.form.fileList.slice()
      newFileList.splice(index, 1)
      this.form.fileList = newFileList
    },
    // 文件上传之前的检查
    beforeUpload(file) {
      const fileName = file.name
      const pos = fileName.lastIndexOf('.')
      const lastName = fileName.substring(pos, fileName.length)
      if (
        lastName.toLowerCase() !== '.zip' &&
              lastName.toLowerCase() !== '.xml' &&
              lastName.toLowerCase() !== '.bpmn20.xml' &&
              lastName.toLowerCase() !== '.bpmn' &&
              lastName.toLowerCase() !== '.bar'
      ) {
        this.$message.error('文件必须为.zip,.bpmn20.xml,.bpmn,.bar类型')
        this.form.fileList = []
      } else {
        this.form.fileList = [file]
      }
      return false
    }
  }
}
</script>
